package com.chung.sean;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Test program to save files to internal memory on phone.
 * In theory easily portable to other applications to save any other kind of content.
 * ONLY files specific to application currently in use are applicable. 
 * Files saved will ONLY be accessible to single application.
 * Files may be viewed, or deleted. 
 * 
 * @author Sean Chung
 *
 */
public class IOTestActivity extends Activity {
 
  // Content added by user.
  private EditText input;
  // Content to be displayed.
  private String fileContent;
  // Array of file names.
  private String[] fileNames;
  // Name of file being accessed
  private String storedFile;
  // Default displays.
  private String defaultContent = "File content goes here";
  
  // Layout elements.
  private Button saveButton,deleteButton;
  private ListView fileDisplay;   
  private TextView displayContent;
 
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    input = (EditText)findViewById(R.id.input);
    saveButton = (Button)findViewById(R.id.save);
    deleteButton = (Button)findViewById(R.id.delete);
    fileDisplay = (ListView)findViewById(R.id.list);
    displayContent = (TextView)findViewById(R.id.display);
    
    displayContent.setText(defaultContent);
    deleteButton.setEnabled(false); // Disable delete button until a file is selected.
    
    listSavedFiles(); //List current saved files.
    
    /**
     * Listener for "save" button.
     * 
     * Prompts user if no content currently entered.
     * Default filename is timestamp in MM-dd-yyyy-hh:mm:ss.SSS format.
     */
    saveButton.setOnClickListener(new Button.OnClickListener() {
      @Override
      public void onClick(View view) {
        FileOutputStream fos = null;
        String fileName = getFileName(System.currentTimeMillis());
        fileContent = input.getText().toString();
          
        // Check if user entered content.
        if (fileContent.trim().equals("")) {
          Toast.makeText(IOTestActivity.this, "Please add content", Toast.LENGTH_SHORT).show();
        }
        else {
          try {
            // Create and save files. Files are only viewable by this application.
            // Assume no duplicates/conflicts since using timestamps for filenames.
            fos = openFileOutput(fileName, Context.MODE_PRIVATE); 
            fos.write(fileContent.getBytes());
            fos.close();
            // Confirmation.
            Toast.makeText(IOTestActivity.this, fileName + " saved.", Toast.LENGTH_SHORT).show();
          } 
          catch (FileNotFoundException e) {
            Toast.makeText(IOTestActivity.this, "Error: " + fileName + " not found.", Toast.LENGTH_SHORT).show();
          } 
          catch (IOException e) {
            Toast.makeText(IOTestActivity.this, "Error: " + fileName + " not saved.", Toast.LENGTH_SHORT).show();
          }
          displayContent.setText(defaultContent); // Reset content area.
          input.setText(""); // Reset input area.
        }
        listSavedFiles(); // List files after new file creation.
      }
    });
      fileDisplay.setOnItemClickListener(listOnClickListener);
    }
    
  /**
   * Display currently saved files. *Files displayed are specific to application*
   */
  private void listSavedFiles() {
    fileNames = getApplicationContext().fileList();
    ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fileNames);
    fileDisplay.setAdapter(adapter);  
  }
    
  /**
   * Listener for ListView items. 
   * Accesses clicked file.
   */
  OnItemClickListener listOnClickListener = new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
    storedFile = (String) parent.getItemAtPosition(position);
    accessFile(storedFile);
    deleteButton.setEnabled(true); // Enable delete button.
  }};
  
  /**
   * Access/View a file.
   * @param file the file to open.
   */
  private void accessFile(final String file) {
     FileInputStream fis = null;
     String content = "";
     
     try {
       fis = openFileInput(file);
       byte[] readContent = new byte[fis.available()]; // Create byte arrary as large as file content.
       
       // Read from file until EOF is reached.
       while (fis.read(readContent) != -1) {
         content += new String(readContent); // Byte to String.
       }       
       fis.close(); // Close stream.
       input.setText(""); // Reset input area.
     } 
     catch (FileNotFoundException e) {
       Toast.makeText(IOTestActivity.this, "Error: " + file + " not found.", Toast.LENGTH_SHORT).show();
     } 
     catch (IOException e) {
       Toast.makeText(IOTestActivity.this, "Error: " + file + " not saved.", Toast.LENGTH_SHORT).show();
     }     
     displayContent.setText(content);
     
     /**
      * Listener for delete button. Only active when viewing a file.
      * Uses dialog to confirm delete.
      */
     deleteButton.setOnClickListener(new Button.OnClickListener() {
       @Override
       public void onClick(View view) {
         
         // Create a new dialog to confirm user wishes to delete file.
         AlertDialog.Builder fileDialog = new AlertDialog.Builder(IOTestActivity.this);
         fileDialog.setTitle("Delete file " + storedFile +" ??");
         fileDialog.setNeutralButton("CANCEL", null); // Cancel button does nothing.
         
         /**
          * Listener for the confirm delete button in dialog.
          */
         OnClickListener confirmDeleteListener = new OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {
             deleteFile(storedFile);
             displayContent.setText(defaultContent);
             
             // Confirmation.
             Toast.makeText(IOTestActivity.this, storedFile + " deleted", Toast.LENGTH_SHORT).show();
             deleteButton.setEnabled(false); // Disable delete button.
             listSavedFiles();
             }};
            
             // Add confirm delete button to dialog.
             fileDialog.setPositiveButton("DELETE", confirmDeleteListener);
             fileDialog.show();  
       }
     });
  }


  /**
   * Converts time in milliseconds to a timestamp string.
   * 
   * @param time current system time in milliseconds
   * @return String timestamp
   */
  private String getFileName(long time) {
    DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy-hh:mm:ss.SSS");
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(time);
        
    return formatter.format(calendar.getTime());
  }
}